"""
结果表格组件
显示车牌识别结果的表格
"""

from pathlib import Path
from typing import List, Dict
from PySide6.QtWidgets import QWidget, QVBoxLayout, QTableWidget, QTableWidgetItem
from PySide6.QtCore import Qt

from src.config import config
from src.utils.logger import app_logger


class ResultsTableWidget(QWidget):
    """
    结果表格组件类
    
    用途：
    - 以表格形式显示识别结果
    - 支持排序和选择
    - 显示详细的识别信息
    """
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
    
    def setup_ui(self):
        """
        设置用户界面
        """
        layout = QVBoxLayout(self)
        
        # 创建表格
        self.table = QTableWidget()
        
        # 从配置读取表格设置
        table_config = config.get('gui.table')
        columns = table_config.get('columns')
        
        self.table.setColumnCount(len(columns))
        self.table.setHorizontalHeaderLabels(columns)
        
        # 设置表格属性
        alternating_colors = table_config.get('alternating_colors')
        self.table.setAlternatingRowColors(alternating_colors)
        
        selection_behavior = table_config.get('selection_behavior')
        if selection_behavior == 'rows':
            self.table.setSelectionBehavior(QTableWidget.SelectRows)
        
        # 设置列宽
        column_widths = table_config.get('column_widths')
        for i, width in enumerate(column_widths):
            if i < self.table.columnCount():
                self.table.setColumnWidth(i, width)
        
        # 最后一列自动拉伸
        self.table.horizontalHeader().setStretchLastSection(True)
        
        layout.addWidget(self.table)
    
    def update_results(self, results: List[Dict]):
        """
        更新表格显示的结果
        
        参数：
            results (List[Dict]): 处理结果列表
        """
        try:
            # 计算总行数
            total_rows = sum(max(1, len(r.get('detections', []))) for r in results)
            self.table.setRowCount(total_rows)
            
            row = 0
            for result in results:
                image_name = Path(result.get('image_path', 'Unknown')).name
                
                if result.get('success', False) and result.get('detections'):
                    # 有检测结果
                    for detection in result['detections']:
                        self._add_detection_row(row, image_name, result, detection)
                        row += 1
                else:
                    # 无检测结果或失败
                    self._add_empty_row(row, image_name, result)
                    row += 1
            
            app_logger.info(f"表格更新完成，共 {total_rows} 行数据")
            
        except Exception as e:
            app_logger.error(f"更新结果表格失败: {e}")
    
    def _add_detection_row(self, row: int, image_name: str, result: Dict, detection: Dict):
        """
        添加检测结果行
        
        参数：
            row (int): 行号
            image_name (str): 图像名称
            result (Dict): 处理结果
            detection (Dict): 检测结果
        """
        # 图像名称
        self.table.setItem(row, 0, QTableWidgetItem(image_name))
        
        # 车牌号
        plate_text = detection.get('processed_text', '')
        self.table.setItem(row, 1, QTableWidgetItem(plate_text))
        
        # 置信度
        confidence = detection.get('confidence', 0)
        conf_item = QTableWidgetItem(f"{confidence:.3f}")
        conf_item.setData(Qt.UserRole, confidence)  # 存储数值用于排序
        self.table.setItem(row, 2, conf_item)
        
        # 是否有效
        is_valid = detection.get('is_valid', False)
        valid_text = "是" if is_valid else "否"
        self.table.setItem(row, 3, QTableWidgetItem(valid_text))
        
        # 处理时间
        processing_time = result.get('processing_time', 0)
        time_item = QTableWidgetItem(f"{processing_time:.2f}s")
        time_item.setData(Qt.UserRole, processing_time)  # 存储数值用于排序
        self.table.setItem(row, 4, time_item)
        
        # 状态
        self.table.setItem(row, 5, QTableWidgetItem("成功"))
    
    def _add_empty_row(self, row: int, image_name: str, result: Dict):
        """
        添加空结果行（无检测结果或失败）
        
        参数：
            row (int): 行号
            image_name (str): 图像名称
            result (Dict): 处理结果
        """
        # 图像名称
        self.table.setItem(row, 0, QTableWidgetItem(image_name))
        
        # 空的车牌号、置信度、有效性
        self.table.setItem(row, 1, QTableWidgetItem(""))
        self.table.setItem(row, 2, QTableWidgetItem(""))
        self.table.setItem(row, 3, QTableWidgetItem(""))
        
        # 处理时间
        processing_time = result.get('processing_time', 0)
        time_item = QTableWidgetItem(f"{processing_time:.2f}s")
        time_item.setData(Qt.UserRole, processing_time)
        self.table.setItem(row, 4, time_item)
        
        # 状态
        if not result.get('success', False):
            status = "失败"
        else:
            status = "无车牌"
        self.table.setItem(row, 5, QTableWidgetItem(status))
    
    def clear_results(self):
        """
        清空表格结果
        """
        self.table.setRowCount(0)
        app_logger.debug("结果表格已清空")
    
    def get_selected_rows(self) -> List[int]:
        """
        获取选中的行号
        
        返回值：
            List[int]: 选中的行号列表
        """
        selected_rows = []
        for item in self.table.selectedItems():
            row = item.row()
            if row not in selected_rows:
                selected_rows.append(row)
        
        return sorted(selected_rows)
    
    def export_to_csv(self, file_path: str) -> bool:
        """
        导出表格数据到CSV文件
        
        参数：
            file_path (str): CSV文件路径
            
        返回值：
            bool: 是否导出成功
        """
        try:
            import csv
            
            with open(file_path, 'w', newline='', encoding='utf-8') as csvfile:
                writer = csv.writer(csvfile)
                
                # 写入表头
                headers = []
                for col in range(self.table.columnCount()):
                    headers.append(self.table.horizontalHeaderItem(col).text())
                writer.writerow(headers)
                
                # 写入数据
                for row in range(self.table.rowCount()):
                    row_data = []
                    for col in range(self.table.columnCount()):
                        item = self.table.item(row, col)
                        if item:
                            row_data.append(item.text())
                        else:
                            row_data.append("")
                    writer.writerow(row_data)
            
            app_logger.info(f"结果表格已导出到: {file_path}")
            return True
            
        except Exception as e:
            app_logger.error(f"导出CSV失败: {e}")
            return False
    
    def get_statistics(self) -> Dict:
        """
        获取表格数据的统计信息
        
        返回值：
            Dict: 统计信息
        """
        stats = {
            'total_rows': self.table.rowCount(),
            'successful_detections': 0,
            'valid_plates': 0,
            'failed_detections': 0,
            'average_confidence': 0.0,
            'average_processing_time': 0.0
        }
        
        if stats['total_rows'] == 0:
            return stats
        
        confidences = []
        processing_times = []
        
        for row in range(self.table.rowCount()):
            # 状态列
            status_item = self.table.item(row, 5)
            if status_item and status_item.text() == "成功":
                stats['successful_detections'] += 1
                
                # 有效性列
                valid_item = self.table.item(row, 3)
                if valid_item and valid_item.text() == "是":
                    stats['valid_plates'] += 1
                
                # 置信度
                conf_item = self.table.item(row, 2)
                if conf_item and conf_item.data(Qt.UserRole) is not None:
                    confidences.append(conf_item.data(Qt.UserRole))
            else:
                stats['failed_detections'] += 1
            
            # 处理时间
            time_item = self.table.item(row, 4)
            if time_item and time_item.data(Qt.UserRole) is not None:
                processing_times.append(time_item.data(Qt.UserRole))
        
        # 计算平均值
        if confidences:
            stats['average_confidence'] = sum(confidences) / len(confidences)
        
        if processing_times:
            stats['average_processing_time'] = sum(processing_times) / len(processing_times)
        
        return stats 